package com.gxitsky.plugin.controller;

import com.gxitsky.plugin.model.BaseResponse;
import com.gxitsky.plugin.model.TestRequest;
import com.gxitsky.plugin.model.TestResponse;
import com.gxitsky.plugin.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author gxing
 * @desc TODO
 * https://blog.csdn.net/m0_38109046/article/details/89449305
 * @date 2022/1/6
 */
@RestController
public class TestController extends BaseController {

    @Autowired
    private TestService testService;

    /**
     * 异步的
     *
     * @param request 接口入参
     * @return BaseResponse
     */
    //https://blog.csdn.net/m0_37595562/article/details/81013909
    @RequestMapping("/async/request")
    public DeferredResult<ResponseEntity<String>> index(HttpServletRequest request, HttpServletResponse response) {
        final DeferredResult<ResponseEntity<String>> deferredResult = new DeferredResult<>();
        new Thread(new AsyncTask(deferredResult)).start();
        System.out.println("-----异步完成-----:" + Thread.currentThread().getName());
        return deferredResult;
    }

    /**
     * 同步的
     *
     * @param request 接口入参
     * @return BaseResponse
     */
    @RequestMapping("/test1")
    public BaseResponse test1(TestRequest request) {
        TestResponse response = new TestResponse();
        System.out.println("1:" + Thread.currentThread().getName());
        process(request, response, () -> {
            System.out.println("2:" + Thread.currentThread().getName());
            testService.test1(request, response);
        });
        System.out.println("4:" + Thread.currentThread().getName());
        return response;
    }

    /**
     * 异步的
     *
     * @param request 接口入参
     * @return BaseResponse
     */
    @RequestMapping("/test2")
    public BaseResponse test2(TestRequest request) {
        TestResponse response = new TestResponse();
        System.out.println("1:" + Thread.currentThread().getName());
        process(request, response, () -> new Thread(() -> {
            System.out.println("2:" + Thread.currentThread().getName());
            testService.test1(request, response);
        }).start());
        System.out.println("4:" + Thread.currentThread().getName());
        return response;
    }
}
